package com.oswift.cms.web.backstage;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.oswift.cms.entity.AdminBean;
import com.oswift.cms.entity.AnnounceBean;
import com.oswift.cms.entity.ChannelBean;
import com.oswift.cms.entity.CommonModelBean;
import com.oswift.cms.entity.DictionaryBean;
import com.oswift.cms.entity.ErrorBean;
import com.oswift.cms.entity.MessageBean;
import com.oswift.cms.entity.PageBean;
import com.oswift.cms.service.IAnnounceService;
import com.oswift.cms.service.IChannelService;
import com.oswift.cms.system.cache.CMSCacheFileds;
import com.oswift.cms.system.cache.DictionaryManager;
import com.oswift.cms.utils.Field;
import com.oswift.cms.utils.PageCode;
import com.oswift.cms.utils.Field.PageName;
import com.oswift.utils.cache.ResourceManager;
import com.oswift.utils.common.StringUtil;
import com.oswift.utils.exception.PlatException;

@Controller
@RequestMapping("/security")
public class AnnounceAction extends BaseAction
{
    /**
     * 日志实例
     */
    private static Logger log = LoggerFactory.getLogger(AnnounceAction.class);

    /**
     * FriendSiteServiceImpl注入对象
     */
    @Resource
    private IAnnounceService announceService;

    /**
     * ChannelServiceImpl注入对象
     */
    @Resource
    private IChannelService channelService;

    /**
     *
     * 加载公告新增页面
     *
     * @author zhuou
     */
    @RequestMapping(value = "/loadAddAnnounce", method = RequestMethod.GET)
    public ModelAndView loadAddAnnounce(HttpServletRequest request)
    {
        ModelAndView mv = null;
        try
        {
            AdminBean adminBean = this.getAdmin(request);
            int companyId = adminBean.getCompanyID();

            mv = announceService.loadAddAnnounce(PageName.ANNOUNCE, companyId);
            mv.addObject(METHOD, METHOD_ADD);
        }
        catch (PlatException e)
        {
            log.error("The method of loadAddAnnounce is error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(ResourceManager.getValue(e.getExceptionCode()));
            mv.addObject("bean", bean);
        }
        catch (Exception e)
        {
            log.error("The method of loadAddAnnounce is system's error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(PageCode.SYSTEM_ERROR);
            bean.setMessInfo(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
            mv.addObject("bean", bean);
        }
        return mv;
    }

    /**
     *
     * 加载公告修改页面
     *
     * @author zhuou
     */
    @RequestMapping(value = "/loadUpdateAnnounce", method = RequestMethod.GET)
    public ModelAndView loadUpdateAnnounce(HttpServletRequest request)
    {
        ModelAndView mv = null;
        try
        {
            String id = request.getParameter("id");
            if (StringUtil.isEmpty(id))
            {
                mv = new ModelAndView(PageName.ERROR_PAGE);
                ErrorBean bean = new ErrorBean();
                bean.setCode(PageCode.GET_WEBPARAM_FAIL);
                bean.setMessInfo(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                mv.addObject("bean", bean);
                return mv;
            }
            AdminBean adminBean = this.getAdmin(request);
            int companyId = adminBean.getCompanyID();

            mv = announceService.loadUpdateArticle(PageName.ANNOUNCE,
                    companyId, Integer.valueOf(id));
            mv.addObject(METHOD, METHOD_UPDATE);
        }
        catch (PlatException e)
        {
            log.error("The method of loadUpdateAnnounce is error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(ResourceManager.getValue(e.getExceptionCode()));
            mv.addObject("bean", bean);
        }
        catch (Exception e)
        {
            log.error("The method of loadUpdateAnnounce is system's error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(PageCode.SYSTEM_ERROR);
            bean.setMessInfo(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
            mv.addObject("bean", bean);
        }
        return mv;
    }

    /**
     *
     * 添加公告信息
     *
     * @author zhuou
     */
    @RequestMapping(value = "/addAnnounce", method = RequestMethod.POST)
    @ResponseBody
    public Object addAnnounce(HttpServletRequest request)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            AnnounceBean bean = getPageData(request);
            if (StringUtil.isEmpty(bean.getTitle())
                    || StringUtil.isEmpty(bean.getContent())
                    || bean.getChannelId() <= 0)
            {
                messBean.setCode(PageCode.TEXTFIELD_ISNOT_EMPTY);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.TEXTFIELD_ISNOT_EMPTY));
                return messBean;
            }
            AdminBean adminBean = this.getAdmin(request);
            bean.setCompanyId(adminBean.getCompanyID());
            bean.setTableName(Field.TableName.ANNOUNCE);
            bean.setInputer(adminBean.getAdminName());

            boolean isSuccess = announceService.save(bean);
            if (isSuccess)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.ANNOUNCE_ADD_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.ANNOUNCE_ADD_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.ANNOUNCE_ADD_FAIL));
            }
        }
        catch (PlatException e)
        {
            log.error("The method of addAnnounce is error.", e);
            messBean.setCode(e.getExceptionCode());
            messBean.setContent(ResourceManager.getValue(e.getExceptionCode()));
        }
        catch (Exception e)
        {
            log.error("The method of addAnnounce is system's error.", e);
            messBean.setCode(PageCode.SYSTEM_ERROR);
            messBean.setContent(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
        }
        return messBean;
    }

    /**
     *
     * 修改公告信息
     *
     * @author zhuou
     */
    @RequestMapping(value = "/updateAnnounce", method = RequestMethod.POST)
    @ResponseBody
    public Object updateAnnounce(HttpServletRequest request)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            AnnounceBean bean = getPageData(request);
            if (bean.getCommonModelId() <= 0)
            {
                messBean.setCode(PageCode.GET_WEBPARAM_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                return messBean;
            }

            if (StringUtil.isEmpty(bean.getTitle())
                    || StringUtil.isEmpty(bean.getContent())
                    || bean.getChannelId() <= 0)
            {
                messBean.setCode(PageCode.TEXTFIELD_ISNOT_EMPTY);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.TEXTFIELD_ISNOT_EMPTY));
                return messBean;
            }

            boolean isSuccess = announceService.update(bean);
            if (isSuccess)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.ANNOUNCE_UPDATE_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.ANNOUNCE_UPDATE_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.ANNOUNCE_UPDATE_FAIL));
            }
        }
        catch (PlatException e)
        {
            log.error("The method of updateAnnounce is error.", e);
            messBean.setCode(e.getExceptionCode());
            messBean.setContent(ResourceManager.getValue(e.getExceptionCode()));
        }
        catch (Exception e)
        {
            log.error("The method of updateAnnounce is system's error.", e);
            messBean.setCode(PageCode.SYSTEM_ERROR);
            messBean.setContent(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
        }
        return messBean;
    }

    /**
     *
     * 删除公告信息
     *
     * @author zhuou
     */
    @RequestMapping(value = "/delAnnounce", method = RequestMethod.POST)
    @ResponseBody
    public Object delAnnounce(HttpServletRequest request)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            String id = request.getParameter("id");
            if (StringUtil.isEmpty(id))
            {
                messBean.setCode(PageCode.GET_WEBPARAM_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                return messBean;
            }

            int delSuccessNum = 0;
            int delFailNum = 0;
            String[] array = id.split(Field.COMMA);
            for (String i : array)
            {
                boolean isSuccess = announceService.delete(Integer.valueOf(i));
                if (isSuccess)
                {
                    delSuccessNum++;
                }
                else
                {
                    delFailNum++;
                }
            }
            if (delSuccessNum == array.length)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.ANNOUNCE_DEL_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.ANNOUNCE_DEL_FAIL);
                String mess = ResourceManager
                        .getValue(PageCode.ANNOUNCE_DEL_FAIL);
                messBean.setContent(StringUtil.replace(mess, String
                        .valueOf(delSuccessNum), String.valueOf(delFailNum)));
            }
        }
        catch (PlatException e)
        {
            log.error("The method of delAnnounce is error.", e);
            messBean.setCode(e.getExceptionCode());
            messBean.setContent(ResourceManager.getValue(e.getExceptionCode()));
        }
        catch (Exception e)
        {
            log.error("The method of delAnnounce is system's error.", e);
            messBean.setCode(PageCode.SYSTEM_ERROR);
            messBean.setContent(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
        }
        return messBean;
    }

    /**
     *
     * 获取公共内容信息
     *
     * @author zhuou
     */
    @RequestMapping(value = "/getAnnounceList", method = RequestMethod.GET)
    public ModelAndView getAnnounceList(HttpServletRequest request)
    {
        ModelAndView mv = null;
        try
        {
            String orderField = request.getParameter("orderField");
            String orderType = request.getParameter("orderType");
            String s_Status = request.getParameter("status");
            String s_ChannelId = request.getParameter("channelId");
            String searchType = request.getParameter("searchType");
            String keyword = request.getParameter("keyword");
            String s_PageNum = request.getParameter("pageNum");

            int status = Field.Status.ALL;
            if (!StringUtil.isEmpty(s_Status))
            {
                status = Integer.valueOf(s_Status);
            }
            int channelId = -1;
            if (!StringUtil.isEmpty(s_ChannelId))
            {
                channelId = Integer.valueOf(s_ChannelId);
            }
            int pageNum = DEFAULT_PAGENUM;
            if (!StringUtil.isEmpty(s_PageNum))
            {
                pageNum = Integer.valueOf(s_PageNum);
            }

            // 权限判断
            AdminBean adminBean = this.getAdmin(request);
            int companyId = adminBean.getCompanyID();

            PageBean<CommonModelBean> bean = announceService.getCommonModel(
                    orderField, orderType, status, channelId, searchType,
                    keyword, this.pageRecordNum, pageNum,
                    Field.TableName.ANNOUNCE, companyId);

            // 获取包含文章板块的栏目
            DictionaryBean dictionaryBean = DictionaryManager
                    .getValue(CMSCacheFileds.BusinessField.DEFAULT_ANNOUNCE_KEY);
            List<ChannelBean> channelList = channelService.getChannelList2(
                    companyId, dictionaryBean.getFieldValue());

            mv = new ModelAndView(PageName.ANNOUNCELIST);
            mv.addObject("pageBean", bean);
            mv.addObject("status", status);
            mv.addObject("channels", channelList);
            mv.addObject("orderType", orderField + "_" +orderType);
            mv.addObject("channelId", channelId);
        }
        catch (PlatException e)
        {
            log.error("Get AnnounceList info is error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(e.getMessage());
            bean.setUrl("getAnnounceList.html");
            mv.addObject("bean", bean);
        }

        return mv;
    }

    /**
     *
     * 公告详情
     *
     * @author zhuou
     */
    @RequestMapping(value = "/announceDetail", method = RequestMethod.GET)
    public ModelAndView announceDetail(HttpServletRequest request)
    {
        ModelAndView mv = null;
        try
        {
            String id = request.getParameter("id");
            if (StringUtil.isEmpty(id))
            {
                mv = new ModelAndView(PageName.ERROR_PAGE);
                ErrorBean bean = new ErrorBean();
                bean.setCode(PageCode.GET_WEBPARAM_FAIL);
                bean.setMessInfo(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                mv.addObject("bean", bean);
                return mv;
            }

            AnnounceBean bean = announceService.getOne(Integer.valueOf(id));
            mv = new ModelAndView(PageName.ANNOUNCE_DETAIL);
            mv.addObject("announceBean", bean);
        }
        catch (PlatException e)
        {
            log.error("The method of announceDetail is error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(ResourceManager.getValue(e.getExceptionCode()));
            mv.addObject("bean", bean);
        }
        catch (Exception e)
        {
            log.error("The method of announceDetail is system's error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(PageCode.SYSTEM_ERROR);
            bean.setMessInfo(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
            mv.addObject("bean", bean);
        }
        return mv;
    }

    /**
     *
     * 从页面提交获取数据
     *
     * @author zhuou
     */
    private AnnounceBean getPageData(HttpServletRequest request)
    {
        String author = request.getParameter("author");
        String sChannelId = request.getParameter("channelId");
        String sCommonModelId = request.getParameter("commonModelId");
        String content = request.getParameter("content");
        String sDayHits = request.getParameter("dayHits");
        String sEliteLevel = request.getParameter("eliteLevel");
        String sHits = request.getParameter("hits");
        String keyword = request.getParameter("keyword");
        String sMonthHits = request.getParameter("monthHits");
        String sOutTime = request.getParameter("outTime");
        String sPriority = request.getParameter("priority");
        String publishTime = request.getParameter("publishTime");
        String sStatus = request.getParameter("status");
        String title = request.getParameter("title");
        String updateTime = request.getParameter("updateTime");
        String sWeekHits = request.getParameter("weekHits");

        AnnounceBean bean = new AnnounceBean();
        bean.setAuthor(author);
        if (StringUtil.isEmpty(sChannelId))
        {
            bean.setChannelId(0);
        }
        else
        {
            bean.setChannelId(Integer.valueOf(sChannelId));
        }
        if (StringUtil.isEmpty(sCommonModelId))
        {
            bean.setCommonModelId(0L);
        }
        else
        {
            bean.setCommonModelId(Long.parseLong(sCommonModelId));
        }
        bean.setContent(content);
        if (StringUtil.isEmpty(sDayHits))
        {
            bean.setDayHits(0);
        }
        else
        {
            bean.setDayHits(Integer.valueOf(sDayHits));
        }
        if (StringUtil.isEmpty(sEliteLevel))
        {
            bean.setEliteLevel(0);
        }
        else
        {
            bean.setEliteLevel(Integer.valueOf(sEliteLevel));
        }
        if (StringUtil.isEmpty(sHits))
        {
            bean.setHits(0);
        }
        else
        {
            bean.setHits(Integer.valueOf(sHits));
        }
        bean.setKeyword(keyword);
        if (StringUtil.isEmpty(sMonthHits))
        {
            bean.setMonthHits(0);
        }
        else
        {
            bean.setMonthHits(Integer.valueOf(sMonthHits));
        }
        if (StringUtil.isEmpty(sOutTime))
        {
            bean.setOutTime(0);
        }
        else
        {
            bean.setOutTime(Double.parseDouble(sOutTime));
        }
        if (StringUtil.isEmpty(sPriority))
        {
            bean.setPriority(0);
        }
        else
        {
            bean.setPriority(Integer.valueOf(sPriority));
        }
        bean.setPublishTime(publishTime);
        bean.setStatus(Integer.valueOf(sStatus));
        bean.setTitle(title);
        bean.setUpdateTime(updateTime);
        if (StringUtil.isEmpty(sWeekHits))
        {
            bean.setWeekHits(0);
        }
        else
        {
            bean.setWeekHits(Integer.valueOf(sWeekHits));
        }

        return bean;
    }

    public void setAnnounceService(IAnnounceService announceService)
    {
        this.announceService = announceService;
    }

    public void setChannelService(IChannelService channelService)
    {
        this.channelService = channelService;
    }
}